import { login, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import storage from "@/utils/storage";
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: ""
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    // console.log(commit , userInfo);
    const { userName, password } = userInfo;
    // console.log(userInfo);
    return new Promise((resolve, reject) => {
      login({ userName: userName.trim(), password: password })
        .then(res => {
          console.log(res);
          commit("SET_TOKEN", res.token);
          // commit('SET_USERID',res.userInfo)
          storage.setStorage("userInfo", res.userinfo);
          storage.setStorage("menus", res.menus);
          setToken(res.token);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      let id = JSON.parse(localStorage.getItem("userInfo")).id;
      getInfo(id)
        .then(res => {
          console.log(res);
          commit("SET_NAME", res.result.userName);
          commit("SET_AVATAR", res.result.avatar);
          resolve(res);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
